package cn.gok.springboot.Controller;

import cn.gok.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author HP
 * @Date 15:11 2022/7/14
 * @Version 1.0
 **/
//@Controller
@RestController
@RequestMapping("/user")//通常实体类的小写
public class UserController {
    @Autowired
    private User user;
    ModelAndView md=new ModelAndView();
    List<User> list =new ArrayList();
    @RequestMapping("/findOne")
    public ModelAndView findOne(){
//        新建模型和视图对象
//        ModelAndView md=new ModelAndView();
//        新建用户对象,通过构造方法进行传值
//        使用set进行赋值
        user.setAge(20);
        user.setName("老白");
        user.setPassword("1123654");
//        attributeName:属性名
        md.addObject("users",user);//传递数据
        md.setViewName("user");
        return md;
    }

//    方式二
//    @RequestMapping("/findOne")
//    public String findOne(Model model){
////        model模型存放数据
//        user.setAge(30);
//        user.setName("老白");
//        user.setPassword("1123654");
//        model.addAttribute("users",user);
//        return "user";
//    }
@RequestMapping("/findAll")
    public ModelAndView findAll(){
        User user = new User(19, "zs", "123456");
        User user1 = new User(20, "ls", "123456");
        User user2 = new User(21, "w5", "123456");
        User user3 = new User(22, "l6", "123456");
        Collections.addAll(list,user,user1,user2,user3);
        System.out.println(list);
        md.addObject("list",list);
        md.setViewName("userlist");
        return md;
    }
    @RequestMapping("/del")
    public String delUser(@RequestParam int age){ //RequestParam请求参数
//       用户存储在list里面,通过遍历，get(i).getage()==this.age,拿到对应的yonghu
        for(int i=0;i<list.size();i++){
            if(list.get(i).getAge()==age){
                list.remove(i);
                return "删除成功";
            }
        }
        return "删除失败";
    }
}
